package com.keur.money.ui.market.impl

import android.content.Context
import com.keur.money.R
import com.keur.money.app.MyApp
import com.keur.money.http.ApiService
import com.keur.money.http.ApiService.addCommonParams
import com.keur.money.http.ApiService.addRandomParams
import com.keur.money.http.HttpHelper
import com.keur.money.http.IHttpCallback
import com.keur.money.mvp.presenter.MvpPresenter
import com.keur.money.status.StatusRepository
import com.keur.money.ui.market.view.IKeurOrderDetailsView
import com.keur.money.utils.helper.KeurCommentDialogHelper
import com.keur.money.utils.helper.KeurCustomConfigsHelper
import com.keur.money.utils.helper.KeurUserPointsHelper
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/8/7 13:45
 * @Annotation：贷款详情 Presenter 实现
 */
class KeurOrderDetailsPresenterImpl(context: Context?) : MvpPresenter<IKeurOrderDetailsView>(context) {

    /**
     * 获取贷款状态信息
     */
    fun loadMullaOrderStatusAction(){
        val httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.KEUR_API_PROCESS_PATH)
        val params = JSONObject().addCommonParams().addRandomParams()
        params.put("product",mvpView?.loadProductName())
        params.put("token",mvpView?.loadProductToken())
        HttpHelper.postKeurAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        if (obj != null) {

                            //1、判断是否存在 订单状态
                            if (obj.has("orderStatus")){
                                val orderStatus = obj.optString("orderStatus")
                                //待还款
                                if (StatusRepository(null,orderStatus).isRepayNow()){
                                    mvpView?.hideMullaLoading()
                                    mvpView?.showMullaOrderRepayViews(obj)
                                    return
                                }
                                //放款中
                                if (StatusRepository(null,orderStatus).isDisbursing()){
                                    obj.put("eventRemark","ApplyLending Page")
                                    mvpView?.showMullaOrderLendingViews(obj)
                                    return
                                }
                                //申请贷款被拒绝
                                if (StatusRepository(null,orderStatus).isRejected()){
                                    obj.put("eventRemark","ApplyFailed Page")
                                    mvpView?.showMullaOrderRejectedViews(obj)
                                    return
                                }
                            }

                            //2、判断是否存在 贷款申请状态
                            if (obj.has("applyStatus")){
                                val applyStatus = obj.optString("applyStatus")
                                //审核中
                                if (StatusRepository(applyStatus).isReviewing()){
                                    obj.put("eventRemark","ApplyAudit Page")
                                    mvpView?.showMullaOrderAuditViews(obj)
                                    return
                                }
                                //被拒绝
                                if (StatusRepository(applyStatus).isRejected()){
                                    obj.put("eventRemark","ApplyFailed Page")
                                    mvpView?.showMullaOrderRejectedViews(obj)
                                    return
                                }
                            }
                        }
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView?.showMullaToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                loadMullaOrderDetails()
            }
        })
    }

    /**
     * 获取贷款信息
     */
    private fun loadMullaOrderDetails(){
        val httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.KEUR_API_ORDER_DETAILS_PATH)
        val params = JSONObject().addCommonParams().addRandomParams()
        params.put("product",mvpView?.loadProductName())
        params.put("token",mvpView?.loadProductToken())
        HttpHelper.postKeurAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        if (obj != null) {
                            //显示共用View
                            mvpView?.showMullaOrderCommonViews(obj)
                        }
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView?.showMullaToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView?.hideMullaLoading()
            }
        })
    }

    /**
     * 获取账户列表
     */
    fun loadMullaAccountListAction(){
        val httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.KEUR_API_ACCOUNT_LIST_PATH)
        val params = JSONObject().addCommonParams().addRandomParams().apply {
//            put("path", ApiService.API_PATH.MULLA_API_ACCOUNT_LIST_PATH)
        }
        HttpHelper.postKeurAction(httpUrl, params, object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val array = data.optJSONArray("obj")
                        val accountList = arrayListOf<JSONObject>()

                        if (array != null && array.length() > 0) {
                            for (i in 0..<array.length()) {
                                val item = array.optJSONObject(i)
                                item.put("isEdit", false)
                                accountList.add(item)
                            }
                        }
                        mvpView?.showMullaAccountList(accountList)
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView?.showMullaToast(msg)
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
                mvpView?.hideMullaLoading()
            }
        })
    }

    /**
     * 只有审核中或放款中需要调此接口
     * 获取评分配置
     */
    fun loadMullaScoreCommentAction() {
        val httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.KEUR_API_STAR_COMMENT_PATH)
        val params = JSONObject().addCommonParams().addRandomParams().apply {
//            put("path", ApiService.API_PATH.MULLA_API_STAR_COMMENT_PATH)
        }
        HttpHelper.postKeurAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null) {
                    mvpView?.getContext()?.let {
                        KeurCommentDialogHelper.showStarDialog(it,obj,true)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 添加绑卡
     */
    fun submitMullaBindAccountAction(mobile: String, walletChannel: String, bindFlag:String = "NO"){
        mvpView?.showMullaLoading()
        val httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.KEUR_API_ACCOUNT_ADD_PATH)
        val params = JSONObject().addCommonParams().addRandomParams().apply {
//            put("path", ApiService.API_PATH.MULLA_API_ACCOUNT_ADD_PATH)
            put("walletMobile", mobile)
            put("walletMobileConfirm", mobile)
            put("walletChannel", walletChannel)
            put("addBindFlag", bindFlag)
        }
        HttpHelper.postKeurAction(httpUrl, params, object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                //刷新列表
                loadMullaAccountListAction()
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj") ?: JSONObject()
                        //新增账户成功，需要增加积分
                        KeurUserPointsHelper.saveMullsUserPointsAction("addAccount", MyApp.app.getString(
                            R.string.points_use_info_add_account), KeurCustomConfigsHelper.getMullaAddAccountPoints())

                        // "YES/NO 是否需要提示用户这个号码可以绑另一个渠道的钱包"
                        val addBindFlag = obj.optString("addBindFlag")
                        if (addBindFlag == "YES") {
                            //需要提示绑定另一个渠道账户
                            var otherAccountInfo: JSONObject? = null

                            //用于从APP配置中获取（walletChannels）对应的信息
                            val channel = obj.optString("channel")
                            if (channel.isNotBlank()) {
                                val customize = KeurCustomConfigsHelper.getMullaConfigData()
                                if (customize != null) {
                                    val walletChannels = customize.optJSONArray("walletChannels")
                                    if (walletChannels != null && walletChannels.length() > 0) {
                                        for (i in 0..<walletChannels.length()) {
                                            val item = walletChannels.optJSONObject(i)
                                            if (channel == item.optString("value")) {
                                                otherAccountInfo = item
                                                break
                                            }
                                        }
                                    }

                                    // 只有非空的情况下才处理
                                    if (otherAccountInfo != null) {
                                        otherAccountInfo.put("walletMobile", mobile)
                                        //提示绑定另一个渠道账户
                                        mvpView?.showMullaBingAccountOtherDialog(otherAccountInfo)
                                        return
                                    }
                                }
                            }
                        }
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView?.showMullaToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView?.hideMullaLoading()
            }
        })
    }

    /**
     * 只有被拒绝才会调用此接口
     * 清除用户数据 或 获取是否显示删除数据按钮
     */
    fun loadMullaUserClearDataAction(isShowButton: Boolean){
        val httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.KEUR_API_USER_DATA_CLEAR_PATH)
        val params = JSONObject().addCommonParams().addRandomParams().apply {
        }
        if (isShowButton){
            params.put("type","GET")
        } else {
            params.put("type","DROP")
        }
        HttpHelper.postKeurAction(httpUrl, params, object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                mvpView?.hideMullaLoading()
                when(data.optInt("code")) {
                    0 -> {//成功
                        if (isShowButton){
                            val obj = data.optJSONObject("obj")
                            if (obj != null && obj.has("showDropButton") && obj.optString("showDropButton") == "YES"){
                                mvpView?.showMullaClearDataBtn(true)
                            } else {
                                mvpView?.showMullaClearDataBtn(false)
                            }
                        } else {
                            mvpView?.showMullaClearDataSuccess()
                        }
                    }
                     else -> {
                         val msg = data.optString("msg")
                         mvpView?.showMullaToast(msg)
                     }
                }
            }
            override fun onRequestError(error: JSONObject) {
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
                mvpView?.hideMullaLoading()
            }
        })
    }
}